package com.yingdong.logic.controller;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.yingdong.db.Userpet;
import com.yingdong.logic.appconst.PetConst;
import com.yingdong.logic.domain.GameUser;
import com.yingdong.message.AlertMessage;
import com.yingdong.message.PetMessage;

public class PetController extends GameController {

	private Map<Integer, Userpet> petList = new ConcurrentHashMap<>();

	public PetController(GameUser user) {
		super(user);

	}

	@Override
	public void init() {
		List<Userpet> list = Userpet.getInstance().selectObjectsByCondition("userId", getUserId());
		for (Userpet pet : list) {
			petList.put(pet.getPos(), pet);
		}
	}

	@Override
	public void firstEnter() {
		new PetMessage(petList.values()).sendToClient(getSessionId());
	}

	@Override
	public void saveDB() {
		Userpet.getInstance().saveBatch(petList.values());
	}

	public int findNearestPos() {
		int pos = 0;
		while (!petList.containsKey(pos)) {
			pos++;
		}
		return pos;
	}

	public void addPet(int petEntId) {
		if (petList.size() >= PetConst.MAX_PET_NUM) {
			new AlertMessage(10).sendToClient(getSessionId());
			return;
		}
		Userpet userpet = new Userpet();
		userpet.setPos(findNearestPos());
		userpet.setUserId(user.getUserId());
		userpet.setEntId(petEntId);
		userpet.setName("");
		userpet.setAffinity(0);
		userpet.setCharm(0);
		userpet.setClean(0);
		userpet.setClose(0);
		userpet.setEndurance(0);
		userpet.setHealth(0);
		userpet.setHunger(0);
		userpet.setIntelligence(0);
		userpet.setLevel(1);
		userpet.setMood(0);
		userpet.setStage(1);
		userpet.setStrength(0);
		userpet.setThirsty(0);
		userpet.setTired(0);
		userpet.setVitality(0);
		petList.put(userpet.getPos(), userpet);
		new PetMessage(petList.values()).sendToClient(getSessionId());
	}

	public void removePet(int petId) {
		Userpet userpet = getUserPetById(petId);
		if (userpet == null)
			return;
		petList.remove(userpet);
		new PetMessage(petList.values()).sendToClient(getSessionId());
	}

	public Userpet getUserPetByPos(int pos) {
		return petList.get(pos);
	}

	public Userpet getUserPetById(int id) {
		for (Userpet pet : petList.values()) {
			if (pet.getId() == id)
				return pet;
		}
		return null;
	}
}
